import os,re,sys,subprocess
from modules import base
from conf import settings
class System(base.Base):
    def __init__(self,host_dict=None):
        self.command=r"""echo `dmidecode -t system | grep -E "Manufacturer"`;echo `dmidecode -t system | grep -E "Product Name"`;echo `dmidecode -t system | grep -E "Serial Number"`;echo "hostname:`hostname`";echo "physical_cpu:`cat /proc/cpuinfo| grep "physical id"| sort| uniq| wc -l`";echo "mode:`cat /proc/cpuinfo | grep "model name" | head -1 | sed  's/model.*://' | sed -r 's/^\s+//g'`";\
echo "cores:`cat /proc/cpuinfo| grep "processor"| wc -l`";echo `ip ad li %s | grep "inet" | awk '{print $1,":",$2}' | sed s/[[:space:]]//g | tail -1`;echo `ip ad li %s | grep "inet" | awk '{print $1,":",$2}' | sed s/[[:space:]]//g | head -1` """%(settings.manageer_nic_name,settings.manageer_nic_name)

        self.host_dict=host_dict
        self.res_list=[]
        super(System,self).__init__()

    def windows(self):
        tmp_dict={}
        res=os.popen('systeminfo').read()
        manufacturer=re.search('系统制造商.*',res).group().strip('系统制造商:').replace('\n','').strip()
        if re.search('System manufacturer',manufacturer):
            tmp_dict.update({'Manufacturer':'Unknow'})
        else:
            tmp_dict.update({'Manufacturer':manufacturer})
        model=re.search('系统型号.*',res).group().strip('系统型号:').replace('\n','').strip()
        if re.search('System Product Name',model):
            tmp_dict.update({'Product Name':'Unknow'})
        else:
            tmp_dict.update({'Product Name':model})
        if os.path.exists('conf/hostname'):
            Hostname=os.popen('hostname').read()
            with open('conf/hostname','r',encoding='utf-8') as f:
                filename=f.read()
                if Hostname == filename:
                    hostname=re.search('主机名.*',res).group().strip('主机名:').replace('\n','').strip()
                else:
                    hostname=filename
        else:
            with open('conf/hostname','w',encoding='utf-8') as f:
                Hostname=os.popen('hostname').read()
                f.write(os.popen('hostname').read())
                hostname=Hostname
        tmp_dict.update({'hostname':hostname})
        tmp_dict.update({'os_platform':'windows'})
        os_version=re.search('OS 名称.*',res).group().strip('OS 名称:').replace('\n','').strip()
        tmp_dict.update({'os_version':os_version})
        cpu_physical_count=re.search('\d+',re.search('处理器.*',res).group()).group()
        tmp_dict.update({'physical_cpu':cpu_physical_count})
        cpu_count=re.search('\d+',os.popen('wmic cpu get NumberOfCores').read()).group()
        tmp_dict.update({'cores':cpu_count})
        cpu_model=os.popen('wmic cpu get Name').read().strip('Name').replace('\n','').strip()
        tmp_dict.update({'mode':cpu_model})
        sn=os.popen('wmic bios get serialnumber').read().replace('\n','').strip('SerialNumber').strip()
        if re.search('System Serial Number',sn):
           tmp_dict.update({'Serial Number':'Unknow'})
        else:
            tmp_dict.update({'Serial Number':sn})
        if settings.manageer_ipv4 is None:
            tmp_dict.update({'inet':'None'})
        else:
            tmp_dict.update({'inet':settings.manageer_ipv4})
        if settings.manageer_ipv6 is None:
            tmp_dict.update({'ipv6':'None'})
        else:
            tmp_dict.update({'ipv6':settings.manageer_ipv6})
        self.res_list.append(tmp_dict)
        base.data_dict['system_info']=self.res_list
    def linux(self):
        if self.host_dict==None: #如果=None,则证明是agent模式
            res_num=os.system('ip ad li %s'%settings.manageer_nic_name)
            if res_num !=0:
                raise Exception('配置文件指定的manageer_nic_name 不存在!')
            res=os.popen(self.command).read()
            self.parse(res)
            base.data_dict['system_info']=self.res_list

        else: #传入了host_dict，证明是ssh模式
            res=self.ssh(self.host_dict,self.command).decode(encoding='utf-8')
            self.parse(res)
            base.data_dict[self.host_dict['hostname']]['system_info']=self.res_list
    def parse(self,data):
        import platform
        clean=data.split('\n')
        tmp_dict={}
        for i in clean:
            # tmp_dict={}
            tmp=i.split(':')
            if len(tmp) ==2:
                tmp_dict[tmp[0]]=tmp[1]

            elif len(tmp) >2:
                ipv6=i.split(":",1)
                tmp_dict['ipv6']=ipv6[1]

        tmp_dict['os_platform']=platform.system()
        tmp_dict['os_version'] =platform.platform()

        if settings.agent_type == 'agent':
            if os.path.exists('conf/hostname'):
                Hostname=os.popen('hostname').read()
                with open('conf/hostname','r',encoding='utf-8') as f:
                    filename=f.read()
                    if Hostname == filename:
                        hostname=Hostname
                    else:
                        hostname=filename
            else:
                with open('conf/hostname','w',encoding='utf-8') as f:
                    Hostname=os.popen('hostname').read()
                    f.write(os.popen('hostname').read())
                    hostname=Hostname

            for item in self.res_list:
                for k,v in item.items():
                    if k =='hostname':
                        item[k]=hostname
        self.res_list.append(tmp_dict)